package consul

import "github.com/hashicorp/consul/api"

type KV interface {
	KVGet(key string) (string, error)
	KVPut(key string, val string) error
}

func (c *consul) KVGet(key string) (string, error) {
	if c.client == nil {
		client, err := c.newClient()

		if err != nil {
			return "", err
		}

		c.client = client
	}

	pair, _, err := c.client.KV().Get(key, nil)
	if err != nil {
		return "", err
	}

	if pair == nil {
		return "", nil
	}

	return string(pair.Value), nil
}

func (c *consul) KVPut(key string, val string) error {
	if c.client == nil {
		client, err := c.newClient()

		if err != nil {
			return err
		}

		c.client = client
	}

	pair := &api.KVPair{
		Key:   key,
		Value: []byte(val),
	}

	_, err := c.client.KV().Put(pair, nil)
	if err != nil {
		return err
	}

	return nil
}
